package com.chen.base.module.redis.config;

import cn.hutool.core.util.StrUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
import org.redisson.config.SingleServerConfig;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @author Long
 */
@Slf4j
@Configuration
@ConditionalOnProperty(value = "spring.data.redis.repositories.enabled", matchIfMissing = true, havingValue = "true")
public class RedissonConfig {
 
    @Value("${spring.redis.host:127.0.0.1}")
    private String host;
    @Value("${spring.redis.port:6379}")
    private String port;
    @Value("${spring.redis.password:}")
    private String password;
 
    /**
     * RedissonClient,单机模式
     */
    @Bean(destroyMethod = "shutdown")
    @SneakyThrows
    public RedissonClient redissonClient(){
        Config config = new Config();
        SingleServerConfig serverConfig = config
                .useSingleServer()
                .setAddress(StrUtil.format("redis://{}:{}",host,port));
        if (StrUtil.isNotBlank(password)){
            serverConfig.setPassword(password);
        }
        // 默认过期时间
        config.setLockWatchdogTimeout(30000);
        log.info("初始化 RedissonClient -> {}", serverConfig.getAddress());
        return Redisson.create(config);
    }
}